//
//  DATabBarViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/26.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DATabBarViewController.h"
#import "DAHomePageViewController.h"
#import "DAPersonalViewController.h"
#import "Utility.h"
#import "DARisingMenu.h"
#import "DASearchBookViewController.h"
#import "DASearchBookDetailViewController.h"
#import "DASearchBookTypeAndHotBookViewController.h"
#import "DADataHandel.h"
#import "SVProgressHUD.h"
#import "DASearchBookDetailModel.h"
#import "DAloginPersonalInformation.h"
#import "DAUploadBookViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "DAMessageDetailViewController.h"
#import "JPUSHService.h"

@interface DATabBarViewController ()<RisingMenuDelegate>{
    UIButton *centerButton;
    DARisingMenu *risingMenu;
    DASearchBookDetailViewController *detailView;
    //MBProgressHUD *hud;
    NSDictionary *dataDic;
}
@property (nonatomic, strong) UINavigationController *nav;
@property (nonatomic, strong) DAloginPersonalInformation *personalInformation;
@end
@implementation DATabBarViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    /** 调用tabBar相关设置的方法 */
    [self ConfigurationTabBar];
    /** 调用创建中间按钮的方法 */
    [self creatButton];
    [self setNotfic];
}
//注册通知
- (void)setNotfic{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectIndex) name:@"selectIndex" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MessageToController:) name:@"MessageToController" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MessageDetail) name:@"ToDetailMessage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshBadge:) name:@"ReceivedMessageForRefreshBadge" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleanTabBarBageValue:) name:@"CleanMessageBadge" object:nil];
}
- (void)refreshBadge:(NSNotification *)not{
    [[self.tabBar.items objectAtIndex:2] setBadgeValue:[NSString stringWithFormat:@"%@", not.object]];
    
}
- (void)selectIndex{
    self.selectedIndex = 0;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"isBorrowSuccessful" object:nil];
     [[self.tabBar.items objectAtIndex:2] setBadgeValue:nil];
    [JPUSHService resetBadge];
}
- (void)MessageToController:(NSNotification *)not{
    NSString *count = [NSString stringWithFormat:@"%@", not.object];
    self.selectedIndex = count.intValue;
   
}
- (void)MessageDetail{
    DAMessageDetailViewController *Message = [[DAMessageDetailViewController alloc]init];
    Message.timelineID = @"257";
    Message.hidesBottomBarWhenPushed = YES;
    [((UINavigationController *)[self.childViewControllers objectAtIndex:2]) pushViewController:Message animated:YES];
    //[self pushViewController:Message animated:YES];
   // [self presentViewController:Message animated:YES completion:nil];
}
#pragma mark - tabBar相关设置
- (void)ConfigurationTabBar{
   // [[self.tabBar.items objectAtIndex:2] setBadgeValue:@"1"];
    self.tabBar.translucent = NO;
    self.tabBar.tintColor = [UIColor supportGreenColor];
//    UITabBarItem *homeItem = [self.tabBar.items objectAtIndex:0];
//    homeItem.image = [UIImage imageNamed:@"tabbar_timeline@3x"];
//    UITabBarItem *personItem = [self.tabBar.items objectAtIndex:3];
//    personItem.image = [UIImage imageNamed:@"tabbar_person@3x"];
//    [homeItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:10],NSFontAttributeName,nil] forState:UIControlStateNormal];
//    [personItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:10],NSFontAttributeName,nil] forState:UIControlStateNormal];
    
}
#pragma mark - 创建中间按钮
- (void)creatButton{
    centerButton = [[UIButton alloc]initWithFrame:CGRectMake(0,-15, 60, 60)];
    centerButton.center = CGPointMake([UIScreen mainScreen].bounds.size.width /2, centerButton.center.y);
    [centerButton setImage:[UIImage imageNamed:@"add@3x"] forState:UIControlStateNormal];
    centerButton.tintColor = [UIColor clearColor];
     centerButton.imageEdgeInsets = UIEdgeInsetsMake(15,15,15,15);
    [centerButton setBackgroundColor:[UIColor supportGreenColor]];
    [centerButton.layer setBorderWidth:5];
    [centerButton.layer setBorderColor:[UIColor whiteColor].CGColor];
    [centerButton.layer setCornerRadius:30];
    centerButton.clipsToBounds = YES;
    [centerButton addTarget:self action:@selector(onTouchAdd:) forControlEvents:UIControlEventTouchUpInside];
    [self.tabBar addSubview:centerButton];
    
}
#pragma mark - 点击发布按钮触发的方法
- (void)onTouchAdd:(id)sender{
    NSLog(@"点击了发布按钮");
    
    NSString *findBook = NSLocalizedString(@"FINDBOOK", nil);
    NSString *OfferringBook = NSLocalizedString(@"OfferringBook", nil);
   // NSString *uploadKnowledge = NSLocalizedString(@"uploadKnowledge", nil);
    NSString *cancelStr = NSLocalizedString(@"cancel", nil);
    
    risingMenu = [[DARisingMenu alloc]initWithButtonTitles:@[findBook, OfferringBook] images:@[@"fabu_book@3x",@"fabu_donate@3x"]];
    risingMenu.delegate = self;
    [risingMenu showOnTouchBlock:^(NSInteger touchIndex) {
        NSLog(@"%ld",(long)touchIndex);
        /** 点击找书 */
        if (touchIndex == 0) {
            UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            DASearchBookTypeAndHotBookViewController *search = [story instantiateViewControllerWithIdentifier:@"HOTBOOKTYPE"];
            UINavigationController *nav = [[UINavigationController alloc]
                                           initWithRootViewController:search];
            [self presentViewController:nav animated:YES completion:^{
                risingMenu.overView.stopMoveLine = YES;
                risingMenu.overView = nil;
                risingMenu = nil;
                [risingMenu.overView.timer invalidate];
                risingMenu.overView.timer = nil;
                [risingMenu.overView removeFromSuperview];
                [risingMenu removeFromSuperview];
            }];
            /** 调用设置导航栏颜色 */
            search.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:cancelStr style:UIBarButtonItemStylePlain target:self action:@selector(disMissViewController)];
          [search.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
        }
        /** 点击献书的时候*/
        else if (touchIndex == 1){
            DAUploadBookViewController *upload = [self.storyboard instantiateViewControllerWithIdentifier:@"DAUploadBookViewController"];
            UINavigationController *nav = [[UINavigationController alloc]
                                            initWithRootViewController:upload];
            [self presentViewController:nav animated:YES completion:^{
                risingMenu.overView.stopMoveLine = YES;
                risingMenu.overView = nil;
                risingMenu = nil;
                [risingMenu.overView.timer invalidate];
                risingMenu.overView.timer = nil;
                [risingMenu.overView removeFromSuperview];
                [risingMenu removeFromSuperview];
            }];
            upload.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:cancelStr style:UIBarButtonItemStylePlain target:self action:@selector(disMissViewController)];
            [upload.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
        }else if (touchIndex == 2){
            
        }
    }];
}
//扫描结果
-(void)didScanFinished:(NSDictionary *)result type:(CodeType)codeType{
    risingMenu.delegate = nil;
    [self getUserID];
    if(codeType == CodeTypeNormal){
    NSString *notFindBook = NSLocalizedString(@"NotFindBook", nil);
        NSLog(@"扫描结果:%@", [result objectForKey:@"code"]);
    NSString *url = DAScanCodeURL;
    NSDictionary *dic = @{@"bookCode": [result objectForKey:@"code"],
                          @"userID": self.personalInformation.userID};
    
    NSLog(@"%@", self.personalInformation.userID);
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
       // NSString *isSuccessful = result[@"result"];
        if ([result[@"result"] isKindOfClass:[NSString class]] &&
            [result[@"result"] isEqualToString:@"false"]) {
            [self loadMBProgress:notFindBook];
            risingMenu.delegate = self;
        } else if ([result[@"result"] isKindOfClass:[NSDictionary class]])  {
            // 跳转到详情页
            dataDic = result[@"result"];
            [self detailBookView];
        } else {
            NSLog(@"DAScanQRCodeURL:数据异常。");
        }
    }];
    }else if (codeType == CodeTypeQR){
        NSString *url = DAScanQRCodeURL;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:result];
        [dic setValue:self.personalInformation.userID forKey:@"userID"];
        [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
            if ([result[@"result"] isKindOfClass:[NSString class]]) {
                if([result[@"result"] isEqualToString:@"true"]){
                    [risingMenu removeFromSuperview];
                }else{
                    
                }
            } else {
                NSLog(@"DAScanQRCodeURL:数据异常。");
            }
            risingMenu.delegate = self;
        }];
    }
}
#pragma mark - 获取userID
- (void)getUserID{
    /** 解档*/
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"DALogin"];
    self.personalInformation = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
#pragma mark - 加载菊花
- (void)loadMBProgress:(NSString *)str{
    [SVProgressHUD showInfoWithStatus:str];
//    hud = [[MBProgressHUD alloc]initWithView:self.view];
//    hud.dimBackground = NO;
//    /** 设置加载文字*/
//    hud.labelText = str;
//    hud.minShowTime = 1;
//    hud.activityIndicatorColor = [UIColor themeWhiteColor];
//    hud.labelColor = [UIColor themeWhiteColor];
//    hud.mode = MBProgressHUDModeText;
//    [[UIApplication sharedApplication].keyWindow addSubview:hud];
//    // [self.view addSubview:self.hud];
//    [hud showAnimated:NO whileExecutingBlock:^{
//    } completionBlock:^{
//        [hud removeFromSuperview];
//        hud = nil;
//    }];
}
#pragma mark - 跳转到图书的详情页
- (void)detailBookView{
    risingMenu.overView.stopMoveLine = YES;
    risingMenu.overView = nil;
    [risingMenu.overView.timer invalidate];
    risingMenu.overView.timer = nil;
    [risingMenu.overView removeFromSuperview];
    [risingMenu removeFromSuperview];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    detailView = [story instantiateViewControllerWithIdentifier:@"SEARCHBOOKDETAIL"];
    detailView.isScanning = YES;
    self.nav = [[UINavigationController alloc] initWithRootViewController:detailView];
    [self presentViewController:self.nav animated:YES completion:nil];
    NSString *cancel = NSLocalizedString(@"cancel", nil);
    detailView.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:cancel style:UIBarButtonItemStylePlain target:self action:@selector(disMissViewController)];
    
    [detailView.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    // 传递 model
    DASearchBookDetailModel *detailModel = [[DASearchBookDetailModel alloc]init];
    detailView.bookID = [[detailModel dataTransformModelWith:dataDic] bookID];
}
#pragma mark - 模态消失
- (void)disMissViewController{
    self.nav = nil;
    self.nav.view = nil;
    risingMenu = nil;
    risingMenu.overView.stopMoveLine = YES;
    risingMenu.overView = nil;
    [risingMenu.overView.timer invalidate];
    risingMenu.overView.timer = nil;
    [risingMenu.overView  removeFromSuperview];
    detailView = nil;
    detailView.bookImage.motionManager = nil;
    detailView.bookImage = nil;
    detailView.view = nil;
    [detailView.view removeFromSuperview];
    [self.nav.view removeFromSuperview];
    [risingMenu removeFromSuperview];
    [self.view removeFromSuperview];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    risingMenu = nil;
    [risingMenu removeFromSuperview];
    [self.view removeFromSuperview];
    [self.view.window removeFromSuperview];
}

#pragma mark - 清除消息页面的角标
- (void)cleanTabBarBageValue:(NSNotification *)not{
    
    [[self.tabBar.items objectAtIndex:2] setBadgeValue:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
